package com.czk.register;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.czk.pojo.URL;
import io.netty.util.CharsetUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/20 10:37
 */
public class ZookeeperRegister {
    private static CuratorFramework client;
    /**
     * 定义本地缓存
     */
    private static Map<String, List<URL>> REGISTER = new ConcurrentHashMap<>(16);

    /**
     * 静态代码块初始化
     */
    static {
        client = CuratorFrameworkFactory.newClient("localhost:2181", new RetryNTimes(3, 1000));
        // 启动客户端
        client.start();
    }

    /**
     * 注册
     *
     * @param interfaceName
     * @param url
     */
    public static void register(String interfaceName, URL url) {
        try {
            Stat stat = client.checkExists().forPath("/dubbo/service/" + interfaceName);
            // 拿到状态
            if (stat == null) {
                List<URL> list = new ArrayList<>();
                list.add(url);
                String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                        .forPath("/dubbo/service/" + interfaceName, JSONArray.toJSONString(list).getBytes());
                System.out.println(result);
            } else {
                // 放入该节点
                byte[] bytes = client.getData().forPath("/dubbo/service/" + interfaceName);
                // 转为json
                JSONArray objects = JSONArray.parseArray(new String(bytes, CharsetUtil.UTF_8));
                String string = JSON.toJSONString(url);
                JSONObject jsonObject = JSONObject.parseObject(string);
                if (!objects.contains(jsonObject)) {
                    objects.add(jsonObject);
                }
                client.create().orSetData().forPath("/dubbo/service/" + interfaceName, JSONArray.toJSONString(objects).getBytes());
            }

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    /**
     * 获取
     *
     * @param interfaceName
     * @return
     */
    public static List<URL> get(String interfaceName) {
        List<URL> cache = REGISTER.get(interfaceName);
        if (cache != null && cache.size() > 0) {
            return cache;
        }
        // 先从map中找
        List<URL> list = null;
        try {
            byte[] bytes = client.getData().forPath("/dubbo/service/" + interfaceName);
            // 转为字符串
            String jsonArray = new String(bytes, CharsetUtil.UTF_8);
            // 解析
            list = JSONArray.parseArray(jsonArray, URL.class);
            if (list != null) {
                REGISTER.put(interfaceName, list);
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return list;
    }
}
